const axios = require('axios');

/**
 * 微信API工具类
 */
class WechatUtil {
  /**
   * 获取微信Access Token
   * @returns {Promise<string>} Access Token
   */
  static async getAccessToken() {
    try {
      const appId = process.env.WX_APP_ID;
      const appSecret = process.env.WX_APP_SECRET;
      
      const response = await axios.get(
        `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`
      );
      
      if (response.data.access_token) {
        return response.data.access_token;
      } else {
        throw new Error('获取微信Access Token失败');
      }
    } catch (error) {
      console.error('获取微信Access Token错误:', error);
      throw error;
    }
  }
  
  /**
   * 获取微信用户信息
   * @param {string} code 授权码
   * @returns {Promise<Object>} 用户信息
   */
  static async getUserInfo(code) {
    try {
      const appId = process.env.WX_APP_ID;
      const appSecret = process.env.WX_APP_SECRET;
      
      // 获取Access Token和OpenID
      const tokenResponse = await axios.get(
        `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${code}&grant_type=authorization_code`
      );
      
      if (tokenResponse.data.errcode) {
        throw new Error(`微信API错误: ${tokenResponse.data.errmsg}`);
      }
      
      const { access_token, openid } = tokenResponse.data;
      
      // 获取用户信息
      const userInfoResponse = await axios.get(
        `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
      );
      
      if (userInfoResponse.data.errcode) {
        throw new Error(`微信API错误: ${userInfoResponse.data.errmsg}`);
      }
      
      return userInfoResponse.data;
    } catch (error) {
      console.error('获取微信用户信息错误:', error);
      throw error;
    }
  }
  
  /**
   * 获取微信JS API配置
   * @param {string} url 当前网页URL
   * @returns {Promise<Object>} JS API配置
   */
  static async getJsApiConfig(url) {
    try {
      const accessToken = await this.getAccessToken();
      
      // 获取jsapi_ticket
      const ticketResponse = await axios.get(
        `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`
      );
      
      if (ticketResponse.data.errcode !== 0) {
        throw new Error(`获取jsapi_ticket错误: ${ticketResponse.data.errmsg}`);
      }
      
      const jsapiTicket = ticketResponse.data.ticket;
      
      // 生成签名
      const nonceStr = this.generateNonceStr();
      const timestamp = Math.floor(Date.now() / 1000);
      
      // 按字典序排序
      const str = `jsapi_ticket=${jsapiTicket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
      const signature = this.sha1(str);
      
      return {
        appId: process.env.WX_APP_ID,
        timestamp,
        nonceStr,
        signature
      };
    } catch (error) {
      console.error('获取微信JS API配置错误:', error);
      throw error;
    }
  }
  
  /**
   * 生成随机字符串
   * @returns {string} 随机字符串
   */
  static generateNonceStr() {
    return Math.random().toString(36).substr(2, 15);
  }
  
  /**
   * SHA1加密
   * @param {string} str 待加密字符串
   * @returns {string} 加密后的字符串
   */
  static sha1(str) {
    const crypto = require('crypto');
    const sha1 = crypto.createHash('sha1');
    sha1.update(str);
    return sha1.digest('hex');
  }
}

module.exports = WechatUtil;
